package com.linkage.jz.bankruptcy.fragment.Project;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.bean.OperLogInfo;
import com.linkage.jz.bankruptcy.bean.ProTask;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.utils.Utils;
import com.linkage.seapeak.activity.message.GoToPageLoadingActivity;

import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.linkage.jz.bankruptcy.utils.Utils.StringToLeng;

/**
 * @author FT
 * @time 2016-07-18 16:49
 * 债权人债权人详情 tab-操作详情
 */

// JUMP 
public class ZQZQUserOperateBaseFragment extends Fragment {
    RecyclerView mRecyclerView;
    private Context context;
    private int mPage;
    public static final String MERCHANT_DETAILS_PAGE = "MERCHANT_DETAILS_PAGE";
    private DemoAdapter mAdapter;

    List<OperLogInfo> mData;
//    private static ZQUserInfo mInfo;
    private static String creditorId;
    private static String proId;

    public static ZQZQUserOperateBaseFragment newInstance(int page, String creditorid, String proid) {
        Bundle args = new Bundle();
        args.putInt(MERCHANT_DETAILS_PAGE, page);
//        mInfo = info;
        proId = proid;
        creditorId = creditorid;
        ZQZQUserOperateBaseFragment tripFragment = new ZQZQUserOperateBaseFragment();
        tripFragment.setArguments(args);
        return tripFragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPage = getArguments().getInt(MERCHANT_DETAILS_PAGE);
        context = getActivity().getApplicationContext();
//        setData();

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_zqbase_oper, container, false);
        mRecyclerView = (RecyclerView) view.findViewById(R.id.mRecyclerView);
        mData = new ArrayList<OperLogInfo>();
                initAdapter(mData);
//        getData();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        getData();
    }

    private void setData(){
//        mFoodData = new ArrayList<>();
//        for(int i=0; i<5;i++){
//            mFoodData.add("美食"+i);
//        }

    }
    /**
     * 设置RecyclerView属性
     */
    private void initAdapter(List<OperLogInfo> data) {
//        mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mAdapter = new DemoAdapter(getActivity(), R.layout.fragment_zqbase_oper_item, data);
        mAdapter.openLoadAnimation();
        mRecyclerView.setAdapter(mAdapter);//设置adapter
        //设置item点击事件
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                OperLogInfo info = mData.get(position);
                switch (view.getId()) {

                    case R.id.rl_flow_add:
//                        CreateProFlowActivity.start(getActivity());
                        break;
                    case R.id.ll_list:
                        operationLogread(info.getId());
                        getToPage(info.getId(), info.getDataId());
                        break;

                }
            }
        });


    }
    /**
     * adapter
     */
    class DemoAdapter extends BaseQuickAdapter<OperLogInfo, BaseViewHolder> {
        int mLayoutId;
        public DemoAdapter(Context context, int LayoutId, List<OperLogInfo> str) {
            super( LayoutId, str);
            mLayoutId = LayoutId;
        }

        @Override
        public void convert(BaseViewHolder helper, OperLogInfo info) {

            long date = StringToLeng(info.getOpAt())*1000;
            String strTime = Utils.timeStamp2Date(date, "yyyy-MM-dd HH:mm:ss");
            helper.setText(R.id.tv_time,strTime);

            String content = "";
            content = info.getDescription();
            helper.setText(R.id.tv_content,content);
            helper.addOnClickListener(R.id.ll_list);

        }
    }


    public void getData()
    {

        if(BankruptcyApp.tokeninfo == null|| BankruptcyApp.tokeninfo.getToken() == null)
        {

            return;
        }
//        ll_nodata.setVisibility(View.GONE);
//        shapeLoadingDialog.setLoadingText("加载中...");
//        shapeLoadingDialog.setCanceledOnTouchOutside(false);
//        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong()+"";
        String timestamp =System.currentTimeMillis()+"";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken","");
        String userId = SPUtils.getInstance(Consts.SPNAME).getString("userId","");

        RequestBody requestBody = new FormBody.Builder()
                .add("appid","1000000001")
                .add("nonce",rom)
                .add("timestamp", timestamp)
                .add("userToken", userToken)
                .add("token", BankruptcyApp.tokeninfo.getToken())
//                .add("token", "")
                .add("pageNumber","1")
                .add("pageSize","100")
                .add("projectId",proId)
            .add("creditorId", creditorId)


                .build();

        String url = Consts.WEBURL_OPERATIONLOG;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {


                String str = response.body().string();
//                if(true)
//                {
//                    str = "{\n" +
//                            "   \"list\": [{\n" +
//                            "      \"id\": \"d8b7336332024acbbeae12238695ba97\",\n" +
//                            "      \"courtHolding\": false,\n" +
//                            "      \"type\": 1,\n" +
//                            "      \"title\": \"api表决重组事项1\",\n" +
//                            "      \"startTime\": 1546128000,\n" +
//                            "      \"endTime\": 1546164000,\n" +
//                            "      \"status\": 2,\n" +
//                            "      \"meeting\": false,\n" +
//                            "      \"meetingTime\": null,\n" +
//                            "      \"vote\": false,\n" +
//                            "      \"voteTime\": null\n" +
//                            "   }],\n" +
//                            "   \"localArrayList\": [1],\n" +
//                            "   \"totalCount\": 1,\n" +
//                            "   \"pageSize\": 10,\n" +
//                            "   \"pageNo\": 1,\n" +
//                            "   \"minPage\": 1,\n" +
//                            "   \"maxPage\": 1,\n" +
//                            "   \"totalPage\": 1\n" +
//                            "}";
//                }
                try{
                    JSONObject object = new JSONObject(str);
                    JSONObject jsondata = object.getJSONObject("data");
                    JSONObject jsonpagination = jsondata.getJSONObject("pagination");
                    OperLogInfo[] array = new Gson().fromJson(jsonpagination.optString("list"),OperLogInfo[].class);
//                    ProVoteInfo[] array = new Gson().fromJson(jsonsubjectList.optString("list"),ProVoteInfo[].class);
                    List<OperLogInfo> list = Arrays.asList(array);
//                        BankruptcyApp.tokeninfo = info;
                    mData.clear();
                    mData.addAll(list);


                    if(mData.size()>0)
                    {

                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
//                                ll_nodata.setVisibility(View.GONE);
//                                mDataRv.setVisibility(View.VISIBLE);
                            }

                        });
                    }else{
                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
//                                ll_nodata.setVisibility(View.VISIBLE);
//                                mDataRv.setVisibility(View.GONE);
                            }

                        });
                    }
                    getActivity().runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            //更新UI
                            mAdapter.notifyDataSetChanged();

                        }

                    });

                }catch (Exception ex)
                {
                    ex.printStackTrace();
                }
            }
        });
    }

    public void getToPage(String id, String msgId) {
        GoToPageLoadingActivity.start(getActivity(), id, 1);
    }


    public void operationLogread(String recordId) {
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");

        Network
                .getAPIService()
                // TODO 是否是管理员需要动态获取
                .operationLogread(userToken, proId,recordId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
//                            super.onNext(json);
                            return;
                        }


                    }

                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                    }
                });
    }
}
